package pattern.prototype;

import java.io.*;

public class Test {
    public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
        Student student = new Student();
        student.setId(1);
        student.setName("张三");
        student.setAge(30);
        student.setGender("男");
        Classz classz = new Classz();
        classz.setId(1);
        classz.setName("一班");
        classz.setCount(50);
        student.setClassz(classz);
        // 浅度克隆
        Student student1 = (Student) student.clone();
        System.out.println(student);
        System.out.println(student1);

        System.out.println(student.getClassz() == student1.getClassz());

        Student student2 = (Student) deepClone(student);
        System.out.println(student.getClassz() == student2.getClassz());

    }
    public static Object deepClone(Object obj) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(obj);//将当前对象写入另一块内存

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);


        return objectInputStream.readObject();


    }
}
